package com.tarena.lbs.basic.web.service;


import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.basic.web.dao.mapper.AdminMapper;
import com.tarena.lbs.basic.web.dao.repository.AdminRepository;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.passport.param.AdminLoginParam;
import com.tarena.lbs.pojo.passport.vo.LoginVO;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class LoginService {

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private JwtEncoder jwtEncoder;


    public LoginVO login(AdminLoginParam adminLoginParam) throws BusinessException {
        log.debug("当前线程是={}",Thread.currentThread().getName());
        AdminPO adminPO = getOneAdminPO(adminLoginParam);
        Asserts.isTrue(adminPO==null,new BusinessException("-2","管理员不存在"));
        Boolean match = StringUtils.equals(adminLoginParam.getPassword(),adminPO.getAccountPassword());
        Asserts.isTrue(!match,new BusinessException("-2","密码错误！"));

        String jwt = CreateJwt(adminPO);

        LoginVO loginVO = new LoginVO(jwt, adminPO.getId(), adminPO.getNickname());
        return loginVO;
    }

    private String CreateJwt(AdminPO adminPO) throws BusinessException {

        UserPrinciple userPrinciple = new UserPrinciple();
        userPrinciple.setId(adminPO.getId());
        userPrinciple.setNickname(adminPO.getNickname());
        userPrinciple.setRole(adminPO.getAccountType()==0? Roles.ADMIN:Roles.SHOP);

        return jwtEncoder.generateToken(userPrinciple);
    }

    private AdminPO getOneAdminPO(AdminLoginParam adminLoginParam) {
        QueryWrapper<AdminPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_phone",adminLoginParam.getPhone());
        AdminPO adminPO = adminRepository.getOne(queryWrapper);
        return adminPO;
    }
}
